package cn.ustb.controller;

import cn.ustb.entity.StudentBasicInformation;
import cn.ustb.entity.User;
import cn.ustb.service.StudentBasicInfoService;
import cn.ustb.serviceImpl.StudentBasicInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author yuyan
 */
@WebServlet("/studentInformationServlet.do")
public class StudentInformationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得学生信息，转换到显示页面显示学生信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        StudentBasicInfoService studentService=new StudentBasicInfoServiceImpl();
        StudentBasicInformation studentBasicInformation=studentService.get(user);
        request.setAttribute("studentBasicInformation", studentBasicInformation);
        request.getRequestDispatcher("/studentInformation.jsp").forward(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //修改学生信息，转换到显示页面显示修改后的学生信息
        System.out.println("-----------------------------");
        StudentBasicInformation sbi = getStuInformation(request);
        System.out.println("==============================");
        System.out.println(sbi);
        //调用DAO修改数据库中的信息
        StudentBasicInfoService studentBasicInfoService=new StudentBasicInfoServiceImpl();
        studentBasicInfoService.update(sbi);

        request.setAttribute("message", "修改成功");
        doGet(request, response);
    }

    private StudentBasicInformation getStuInformation(HttpServletRequest request)throws IOException{
        request.setCharacterEncoding("utf-8");
        StudentBasicInformation sbi;

        Enumeration<String> en = request.getParameterNames();
        List<String> parameterValues = new ArrayList<>();
        while(en.hasMoreElements()){
            parameterValues.add(request.getParameter(en.nextElement()));
        }

        sbi = new StudentBasicInformation(Long.parseLong(parameterValues.get(0)), parameterValues.get(1),
                parameterValues.get(2), parameterValues.get(3), parameterValues.get(4),
                parameterValues.get(5), parameterValues.get(6), parameterValues.get(7),
                parameterValues.get(8), parameterValues.get(9));

        return sbi;
    }
}
